<?php
/**
 *  +----------------------------------------------------------------------
 *  | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 *  +----------------------------------------------------------------------
 *  | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
 *  +----------------------------------------------------------------------
 *  | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 *  +----------------------------------------------------------------------
 *  | Author: CRMEB Team <admin@crmeb.com>
 *  +----------------------------------------------------------------------
 */

/**
 * 商家
 * @author crud自动生成代码
 * @date 2023/10/14 11:11:18
 */

namespace app\adminapi\controller\crud;

use app\adminapi\controller\AuthController;
use app\api\controller\v1\PublicController;
use app\services\system\crontab\SystemCrontabServices;
use think\facade\App;
use app\services\crud\VendorServices;
use think\facade\Db;
use app\Request;
use com\junziqian\sdk\bean\req\sign\ApplySignReq;
use com\junziqian\sdk\bean\req\sign\ext\SignatoryReq;
use com\junziqian\sdk\util\Assert;
use com\junziqian\sdk\util\CommonUtil;
use com\junziqian\sdk\util\RequestUtils;
use crmeb\exceptions\AdminException;
use think\facade\Config;
use app\services\system\attachment\SystemAttachmentServices;

/**
 * Class Vendor
 * @date 2023/10/14
 * @package app\adminapi\controller\crud
 */
class Vendor extends AuthController
{
    private $serviceUrl;
    private $appkey ;
    private $appSecret;
    /**
     * @var VendorServices
     */
    protected $service;

    /**
     * VendorController constructor.
     * @param App $app
     * @param VendorServices $service
     */
    public function __construct(App $app, VendorServices $service)
    {
        parent::__construct($app);
        $this->service = $service;
        $this->serviceUrl = config('jzq')["jzq"]['Url'];
        $this->appkey = config('jzq')["jzq"]['App_Key'];
        $this->appSecret = config('jzq')["jzq"]['App_Secret'];

    }


    /**
     * 列表
     * @date 2023/10/14
     * @return \think\Response
     */
    public function index()
    {
        return app('json')->success($this->service->getCrudListIndex());
    }

    /**
     * 创建
     * @return \think\Response
     * @date 2023/10/14
     */
    public function create()
    {
        return app('json')->success($this->service->getCrudForm());
    }

    /**
     * 保存
     * @return \think\Response
     * @date 2023/10/14
     */
    public function save()
    {
        $data = $this->request->postMore([
            ['name', ''],

        ]);

        validate(\app\adminapi\validate\crud\VendorValidate::class)->check($data);

        $this->service->crudSave($data);

        return app('json')->success(100021);
    }

    /**
     * 编辑获取数据
     * @param $id
     * @return \think\Response
     * @date 2023/10/14
     */
    public function edit($id)
    {
        return app('json')->success($this->service->getCrudForm((int)$id));
    }

    /**
     * 修改
     * @param $id
     * @return \think\Response
     * @date 2023/10/14
     */
    public function update($id)
    {
        if (!$id) {
            return app('json')->fail(100100);
        }

        $data = $this->request->postMore([
            ['name', ''],

        ]);

        validate(\app\adminapi\validate\crud\VendorValidate::class)->check($data);

        $this->service->crudUpdate((int)$id, $data);

        return app('json')->success(100001);
    }

    /**
     * 删除
     * @param $id
     * @return \think\Response
     * @date 2023/10/14
     */
    public function delete($id)
    {
        if (!$id) {
            return app('json')->fail(100100);
        }

        if ($this->service->destroy((int)$id)) {
            return app('json')->success(100002);
        } else {
            return app('json')->success(100008);
        }
    }

    //用户申请入驻商家列表
    public function get_vendor_apply(){
        $page = input("page","1","intval");
        $status = input("status",'');
        $name = input("name",'');
        $phone = input("phone",'');
        $where = [];
        if($status||$status=='0'){
            $where['status'] = $status;
        }
//        if($status==3){
//            unset($where['status']);
//            $where['Sign_status'] = 2;
//        }
        if($name!=''){
            $where[] =['name','like',$name] ;
        }
        if($phone!=''){
            $where[] =['name','like',$name] ;

        }
        $size = 10;
        $list = Db::name('vendor_apply')->where($where)->order('id desc')->limit((($page - 1) * $size),$size)->select()->toArray();
        $list2 = Db::name('vendor_apply')->where($where)->select()->toArray();
        $res = [];
        $res['list'] = $list;
        $res["page"]=$page;
        $res["count"]=count($list2);
        $res["size"]=$size;
        return app('json')->success($res);
    }

    //合同列表
    public function hetong_list(){
        $page = input("page","1","intval");
        $status = input("status",'');
        $name = input("name",'');
        $where = [];
        if($status||$status=='0'){
            $where['status'] = $status;
        }
        if($name!=""){
            $where[] = ['Applicant|Tel|Bankname|Yname|Yphone|Jname|Jphone','like','%'.$name.'%'];
        }
        $size = 10;
        $list = Db::name('contract_entry')->where($where)->limit((($page - 1) * $size),$size)->order('id desc')->select()->toArray();
        $list2 = Db::name('contract_entry')->where($where)->select()->toArray();
        $res = [];
        $res['list'] = $list;
        $res["page"]=$page;
        $res["count"]=count($list2);
        $res["size"]=$size;
        return app('json')->success($res);
    }
    //删除合同
    public function delete_hetong(){
        $id = input("id","");
        if (!$id) return app('json')->fail('参数错误');
        $info = Db::name('contract_entry')->where('id',$id)->find();
        if (!$info) return app('json')->fail('合同数据不存在');
        $d = Db::name('contract_entry')->where('id',$info["id"])->delete();
        if($d>0){
            return app('json')->success('删除成功');
        }else{
             throw new AdminException('删除失败,请稍候再试!');
        }
    }

    //合同详情
    public function get_hetong_details(){
        $id = input("id","");
        if (!$id) return app('json')->fail('参数错误');
        $info = Db::name('contract_entry')->where('id',$id)->find();
        if (!$info) return app('json')->fail('合同数据不存在');
        return app('json')->success($info);
    }

    //后台审核用户申请入驻商
    public function set_apply($id){
        $status = input("status","1","intval");
        $notes = input("notes");
        $data = Db::name('vendor_apply')->where('id',$id)->update(['status'=>$status,'notes'=>$notes]);
        if($data){
            return app('json')->success('审核成功');
        }else{
            return app('json')->success('审核失败');
        }
    }

    //房车入驻合同
    public function signcontract(Request $request){
        $data = $request->postMore([
            ['Type','1'],
            ['Uid',''],
            ['Startdate',''],
            ['Enddate',''],
            ['Jdaibiao',''],
            ['Jdbphone',''],
            ['Applicant',''],
            ['Taxpayer',''],
            ['Address',''],
            ['Tel',''],
            ['Ycar',''],
            ['Deposit',''],
            ['Bank',''],
            ['Bankname',''],
            ['Account',''],
            ['Yname',''],
            ['Yphone',''],
            ['Jname',''],
            ['Jphone',''],
            ['Name',''],
            ['shenfenz',''],
            ['b_paizhao',''],
        ]);
        $data["Createtime"] = time();
//        $res = $this->jzq_post($data);
//        if($res->success=='true'){
//            $data["Contractnumber"] = $res->data;
            $insert = Db::name('contract_entry')->insert($data);
            if($insert){
                return app('json')->success('新增成功');
            }else{
                return app('json')->success(100021);
            }
        }
//        }

    //修改合同信息
    public function update_contract(Request $request){
        $data = $request->postMore([
            ['id','0'],
            ['Uid','2'],
            ['Startdate',''],
            ['Enddate',''],
            ['Jdaibiao',''],
            ['Jdbphone',''],
            ['Applicant',''],
            ['Taxpayer',''],
            ['Address',''],
            ['Tel',''],
            ['Ycar',''],
            ['Deposit',''],
            ['Bank',''],
            ['Bankname',''],
            ['Account',''],
            ['Yname',''],
            ['Yphone',''],
            ['Jname',''],
            ['Jphone',''],
            ['Name',''],
            ['shenfenz',''],
        ]);
        if($data['id']==0){
            return app('json')->fail('请传参数ID');
        }
        $info = Db::name('contract_entry')->where('id',$data['id'])->find();
        if (!$info) return app('json')->fail('合同数据不存在');

        $data["Updatetime"] = time();
        $update = Db::name('contract_entry')->where('id',$data['id'])->update($data);
        if($update){
            return app('json')->success('修改成功');
        }else{
            return app('json')->success('修改失败');
        }
    }

    //君子签创建合同
    public function jzq_post($data){
        //构建请求工具
        $requestUtils=new RequestUtils($this->serviceUrl, $this->appkey, $this->appSecret);
        //CURLFile 可以传url或filePath，但必须保证文件存在且有效，否则php不会报错，只会返回null。
        //初始化合同参数
        $arr= [
            'a_stampname'=>$data['Jdaibiao'],
            'a_stampphone'=>$data['Jdbphone'],
            'b_company'=>$data['Yname'],
            'b_taxid'=>$data['Taxpayer'],
            'b_addr'=>$data['Address'],
            'b_username'=>$data['Name'],
            'b_userphone'=>$data['Yphone'],
            'b_motorhomes'=>$data['Ycar'],//车辆信息
            'startdate'=>$data['Startdate'],
            'enddate'=>$data['Enddate'],
            'manageprice'=>$data['Deposit'],//押金
            'klchbankname'=>$data['Bankname'],//开户名称
            'klchbank'=>$data['Bank'],//开户行
            'klchcard'=>$data['Account'],//银行账户
            'b_stampphone'=>$data['Yphone'],//乙方手机号
        ];
        $arr['startdate'] = date("Y年m月d日",$data['Startdate']);//开始日期
        $arr['enddate'] = date("Y年m月d日",$data['Enddate']);//结束日期
        $arr['createdate'] = date("Y年m月d日",time());//创建日期


        $request=new ApplySignReq();
        $request->contractName=$data['Name']."房车入驻合同";
        $request->serverCa=1;//使用云证书
        $request->fileType = 2;//合同上传方式:0或nu11直接上传PDE;lurl地址下载;2tmpl模版生成;3htm1文件上传
        $request->dealType = 1;//处理方式:为空或0时默认为手签合同(用户有感知);1自动签约(用户无感知);2只保全;5部份自动签;
        $request->templateNo="C005";//模版编号
        $request->templateParams=$arr; //模版变量,可以传array或json_string


        $sReq=new SignatoryReq();
        $sReq->fullName=$data['Name'];
        $sReq->identityType=1;
        $sReq->identityCard=$data["shenfenz"];
        $sReq->mobile=$data['Tel'];
        $sReq->chapteJson="[{\"page\":3,\"chaptes\":[{\"offsetX\":0.12,\"offsetY\":0.23}]},{\"page\":1,\"chaptes\":[{\"offsetX\":0.45,\"offsetY\":0.67}]}]";//array也可以
        $request->signatories=array($sReq);

        //发起PING请求
        $response=$requestUtils->doPost("/v2/sign/applySign",$request);
        if($response->success=="true"){
            return $response;
        }else{
            //处理结果
            print_r(CommonUtil::json_encode($response));
            Assert::notNull($response,"返回的结果不能为空");
            Assert::isTrue($response->success,"处理错误:".CommonUtil::json_encode($response));
        }
        //{"data":"APL1189436984511696896","success":true}
    }

    //后台查看君子签合同信息
    public function get_jzqsign_link(){
        $applyNo = input("applyNo","");
        if (!$applyNo) return app('json')->fail('请传合同编号');
        $requestUtils=new RequestUtils($this->serviceUrl, $this->appkey, $this->appSecret);
        //初始化合同参数
        $request=array(
            "applyNo" => $applyNo //TODO *
        );
        $response=$requestUtils->doPost("/v2/sign/linkAnonyDetail",$request);
        return app('json')->success($response->data);
    }
    //君子签获取文件下载链接
    public function get_jzqsign_xzlink(){
        $applyNo = input("applyNo","");
        if (!$applyNo) return app('json')->fail('请传合同编号');
        $data = Db::name('contract_entry')->where('Contractnumber',$applyNo)->find();
        if (!$data) return app('json')->fail('合同信息不存在');
        $requestUtils=new RequestUtils($this->serviceUrl, $this->appkey, $this->appSecret);
        //初始化合同参数
        $request=array(
            "applyNo" => $applyNo //TODO *
        );
        $response=$requestUtils->doPost("/v2/sign/linkFile",$request);
        if($response->success==1){
            // 下载文件到指定目录
            $url = $response->data;
            $destination = public_path()."/uploads/ht/".$applyNo.'.pdf';
            $wjj = public_path()."/uploads/ht/";
            if(!is_dir($wjj)){
                mkdir($wjj);
            }
                $file_content = file_get_contents($url);
                if ($file_content) {
                    file_put_contents($destination, $file_content);
                    $public = new \app\adminapi\controller\PublicController();
                    $a =  $public->upload_file($destination);
                    $up = Db::name('contract_entry')->where('id',$data['id'])->update(['Contractlink'=>$a['dir']]);
                } else {
                    return app('json')->fail('文件下载失败');
                }
        }
        return app('json')->success("文件同步成功");
    }

    //创建合同的所有门店下拉列表
    public function get_car_staff(){
        $list = Db::name('car_staff')
            ->field('id,login_name,user_name,user_phone')
            ->where(['is_del'=>0])
            ->select()->toArray();
        return app('json')->success($list);
    }

    //上下架车辆sxj_status
    public function sxj_car(){
        $id = input("id","");
        $status = input("status","1");//上下架状态1上架2下架
        if (!$id) return app('json')->fail('参数错误');
        $info = Db::name('car_info')->where('id',$id)->find();
        if (!$info) return app('json')->fail('车辆信息不存在');
        $d = Db::name('car_info')->where('id',$info["id"])->update(['sxj_status'=>$status]);
        if($d>0){
            return app('json')->success('更新成功');
        }else{
            throw new AdminException('更新失败,请稍候再试!');
        }
    }
    //审核车辆car_status
    public function sh_car(){
        $id = input("id","");
        $status = input("status","1");//1审核通过2审核未通过
        if (!$id) return app('json')->fail('参数错误');
        $info = Db::name('car_info')->where('id',$id)->find();
        if (!$info) return app('json')->fail('车辆信息不存在');
        $d = Db::name('car_info')->where('id',$info["id"])->update(['car_status'=>$status]);
        if($d>0){
            return app('json')->success('更新成功');
        }else{
            throw new AdminException('更新失败,请稍候再试!');
        }
    }




}
